<template>
  <!-- 续费设置 -->
  <PageContainer>
    <view class="container bgf">
      <Header title="续费设置" :is-box-shadow="false" />
      <view v-if="reqData" class="top-tips">
        <text>最近修改：{{ reqData?.sysUserName }} {{ reqData?.updateTime }}</text>
      </view>
      <BasicsForm
        @register="formRegister"
        @submit="onSubmit()"
        @on-schema-change="onChange"
        :show-placeholder-view="false"
        :label-width="120"
        :btn-group-options="{
          submit: {
            text: '确认',
          },
        }"
      ></BasicsForm>

      <ShowModal v-model="modalVisible" title="提示" confirm-text="确认" @confirm="handleConfirm">
        <template #content>
          <div>
            <span>确认调整会员信息？</span>
            <span v-if="state == 0" class="report" @click="handleDownLoadReport">查看续费函</span>
          </div>
        </template>
      </ShowModal>
      <ShowModal
        v-model="sendMsgVisible"
        title="续费设置成功"
        cancel-text="暂不发送"
        confirm-text="发送消息"
        :content="`是否需要发送续费通知?`"
        @close="_goBack"
        @confirm="goAddMessage"
      ></ShowModal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /** 续费设置 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import {
    RenewReview,
    RenewDataInfo,
    RenewCreatePaymenrecord,
    Api as adminApi,
    settingInfo,
  } from '@/api/admin';
  import { navigateBack, onLoad, redirectTo } from '@/router';
  import { ref, unref } from 'vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { type FormActionType, type FormSchema, useForm } from '@/components/Form';
  import type {
    IPaymenrecordByIdResult,
    IPaymentRecordExportData,
    ISettingInfoResData,
  } from '@/api/admin/types';
  import { memberTypeGetList } from '@/api/membership';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import { Toast } from '@/utils';
  import { ShareTypeEnum } from '@/enums/shareEnum';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { onShareAppMessage } from '@dcloudio/uni-app';
  import ShowModal from '@/components/ShowModal/index.vue';
  import type { MemberTypeGetListItem } from '@/api/membership/types';
  import { PaymentStatusEnum } from '@/enums/membershipEnum';
  import { useEnv } from '@/hooks/core/useEnv';
  import { useUpload } from '@/hooks/core/useUpload';
  import dayjs from 'dayjs';
  import type { OnchangeArgument } from '@/components/Form/types';
  import dictionary from '@/utils/dictionary';
  import type { MemberRenewSet } from '@/router/types/modules';
import { useAppShare } from '@/hooks/core/useAppShare';

  const modalVisible = ref(false);
  const sendMsgVisible = ref(false);
  const { globalConfig } = useAppStoreWithOut();
  const { setWxSharePath } = useAppShare()

  interface IDefaultData {
    id: number;
    memberName?: string;
    levelName?: string;
    levelId?: number;
    applyType?: number;
    money?: number;
    allottedTime?: number;
  }

  const defaultData = ref<IDefaultData>({
    id: 0,
    memberName: '',
    levelName: '',
    levelId: 0,
    applyType: 1,
  });
  let callback: MemberRenewSet['callback'];

  const reqData = ref<IPaymenrecordByIdResult>();
  const memberInfo = ref<ISettingInfoResData>();
  const selectOptions = ref<{ [x: string]: MemberTypeGetListItem[] }>();
  const reportData = ref<IPaymentRecordExportData>({
    memberName: '',
    levelName: '',
    amountPaid: 0,
    membershipFees: 0,
    applyType: 1,
    unit: 12,
  });

  const state = ref<number>();

  const [register, { getFieldsValue, setFieldsValue, updateSchema, appendSchemaByField }] = useForm(
    {
      labelAlign: 'left',
      validateTrigger: 'bind',
      schemas: [],
    },
  );

  function formRegister(instance: FormActionType) {
    register(instance);
    getRenewDataInfo();
  }

  const formStateDisabled = ref(false);

  const getRenewDataInfo = async () => {
    try {
      memberInfo.value = await settingInfo(defaultData.value?.id);
      reqData.value = await RenewDataInfo(defaultData.value?.id as number);
      const fields: FormSchema[] = [
        {
          field: 'memberName',
          label: '会员名称',
          component: 'Input',
          dynamicDisabled: true,
          defaultValue: reqData.value?.memberName || defaultData.value.memberName,
        },
        {
          field: 'joinTime',
          label: '加入时间',
          component: 'DatePicker',
          dynamicDisabled: true,
          defaultValue: memberInfo.value?.joinTime,
        },
        {
          field: 'nowMemberEndTime',
          label: '到期时间',
          component: 'DatePicker',
          dynamicDisabled: true,
          defaultValue: memberInfo.value?.memberEndTime,
        },
        {
          field: 'nowPaymentStatus',
          label: '当前缴费状态',
          component: 'Input',
          dynamicDisabled: true,
        },
        {
          field: 'levelName',
          label: '当前职务',
          component: 'Input',
          dynamicDisabled: true,
          defaultValue: reqData.value?.levelName || defaultData.value.levelName,
        },
        {
          field: 'levelId',
          label: '续期职务',
          component: 'Select',
          defaultValue: reqData.value?.nowLevelId || defaultData.value.levelId,
          componentProps: {
            localdata: [],
          },
        },
        {
          field: 'standard',
          label: '缴费标准',
          component: 'Input',
          dynamicDisabled: true,
        },
        {
          field: 'payMoney',
          label: '应缴金额',
          component: 'Input',
          isOnChange: true,
          dynamicDisabled: () => formStateDisabled.value,
        },
        {
          field: 'startTime',
          label: '开始时间',
          component: 'DatePicker',
          required: true,
          isOnChange: true,
          defaultValue: reqData.value?.startTime || unref(memberInfo)?.memberEndTime,
        },
        {
          field: 'endTime',
          label: '结束时间',
          component: 'DatePicker',
          required: true,
        },
        {
          field: 'state',
          label: '续费设置',
          component: 'RadioGroup',
          required: true,
          defaultValue: reqData.value?.state || PaymentStatusEnum.NOTPAYCOST,
          isOnChange: true,
          dynamicDisabled: () => formStateDisabled.value,
          componentProps: {
            localdata: [
              { text: '设为待缴费', value: 0 },
              { text: '设为已缴费', value: 1 },
            ],
          },
        },
        {
          field: 'paymentVoucher',
          label: '缴费凭证',
          component: 'UploadImg',
          ifShow: reqData.value && reqData.value?.payMoney <= 0,
          defaultValue: reqData.value?.paymentVoucher,
          componentProps: {
            limit: 1
          }
        },
      ];

      for (let i = 0; i < fields.length; i++) {
        const item = fields[i];
        appendSchemaByField({
          ...item,
        } as FormSchema);
      }

      const typeDataName = [
        { field: 'levelId', type: 'memberLevel' },
        { field: 'memberPostId', type: 'memberPost' },
      ];
      selectOptions.value = await memberTypeGetList(typeDataName.map((v) => v.type));
      for (let index = 0; index < typeDataName.length; index++) {
        const item = typeDataName[index];
        updateSchema({
          field: item.field,
          isOnChange: true,
          componentProps: {
            localdata: localDataMapping(selectOptions.value[item.type], {
              label: 'name',
              value: 'id',
            }),
          },
        });
      }

      let levelItem = selectOptions.value['memberLevel'].find(
        (f) => f.id === defaultData.value.levelId,
      );

      const _allottedTime = unref(reqData)?.allottedTime ?? levelItem?.allottedTime ?? 0;
      const _startTime = unref(reqData)?.startTime ?? unref(memberInfo)?.memberEndTime;
      const money = unref(reqData)?.payMoney ?? levelItem?.membershipFees ?? 0;
      const dicts = dictionary.getLocal('paymentStatus');
      let item = dicts.find((f) => f.dictValue === memberInfo.value?.paymentStatus);

      updateSchema([
        {
          field: 'standard',
          defaultValue: `${money}元/${_allottedTime}月`,
        },
        {
          field: 'payMoney',
          defaultValue: money
        },
        {
          field: 'endTime',
          defaultValue:
            reqData.value?.endTime ||
            dayjs(_startTime)
              .add(_allottedTime as number, 'month')
              .format('YYYY-MM-DD'),
        },
        {
          field: 'nowPaymentStatus',
          defaultValue: item?.dictLabel,
        }
      ]);

      if (Number(money) <= 0) {
        formStateDisabled.value = true;
        setFieldsValue({ state: PaymentStatusEnum.ALREADYPAYCOST });
      }

      reportData.value.memberName = defaultData.value?.memberName;
      reportData.value.levelName = reqData.value?.nowLevelName || levelItem?.name;
      reportData.value.membershipFees = reqData.value?.money ?? levelItem?.membershipFees ?? 0;
      reportData.value.applyType = defaultData.value.applyType;
      reportData.value.unit = _allottedTime;
    } catch (error) {
      console.error(error);
    }
  };

  function onChange(e: OnchangeArgument) {
    if (e.field === 'levelId') {
      let item =
        selectOptions.value && selectOptions.value['memberLevel'].find((f: any) => f.id === e.val);
      setFieldsValue({ standard: `${item?.membershipFees}元/${item?.allottedTime}月` });
      setFieldsValue({ payMoney: item?.membershipFees });
      const { startTime } = getFieldsValue();
      setFieldsValue({
        endTime: dayjs(startTime)
          .add(item?.allottedTime as number, 'month')
          .format('YYYY-MM-DD'),
      });
      const state = item?.membershipFees ? 0 : 1;
      formStateDisabled.value = item?.membershipFees ? false : true;

      setFieldsValue({
        state: state,
      });

      updateSchema([
        {
          field: 'paymentVoucher',
          ifShow: state == PaymentStatusEnum.ALREADYPAYCOST,
        },
      ]);
      reportData.value.levelName = item?.name;
      reportData.value.unit = item?.allottedTime;
      reportData.value.membershipFees = item?.membershipFees;

    } else if (e.field === 'startTime') {
      setFieldsValue({
        endTime: dayjs(e.val)
          .add(unref(reportData).unit as number, 'month')
          .format('YYYY-MM-DD'),
      });
    } else if (e.field === 'state') {
      updateSchema({
        field: 'paymentVoucher',
        ifShow: e.val == PaymentStatusEnum.ALREADYPAYCOST,
      });
    }
  }

  // 下载续费函
  const { getEnv } = useEnv();
  const { openDocument } = useUpload();
  function handleDownLoadReport() {
    let { payMoney, startTime, endTime } = getFieldsValue();
    startTime = dayjs(startTime).format('YYYY-MM-DD');
    endTime = dayjs(endTime).format('YYYY-MM-DD');
    openDocument({
      filePath:
        getEnv('BASE_URL') +
        adminApi.renewExport +
        `?memberName=${defaultData.value.memberName}&levelName=${
          defaultData.value.levelName
        }&nowLevelName=${reportData.value.levelName}&amountPaid=${payMoney}&membershipFees=${
          reportData.value.membershipFees
        }
      &applyType=${reportData.value.applyType}&startTime=${startTime}&endTime=${endTime}&unit=${
          (reportData.value.unit as number) / 12 + '年'
        }&allottedTime=${reportData.value.unit}`,
      fileType: 'pdf',
      customFileName: `${defaultData.value.memberName}-续费缴费函`,
    });
  }

  const onSubmit = () => {
    let { payMoney, state: state2, startTime, endTime } = getFieldsValue();
    state.value = state2;
    if (dayjs(startTime).unix() >= dayjs(endTime).unix()) {
      Toast('结束时间需大于开始时间');
      return;
    }
    if (payMoney == 0 && state2 == 0) return Toast('金额为0无需支付，请设为已缴费');
    modalVisible.value = true;
  };

  const sendUserId = ref<String>();
  function handleConfirm() {
    const { levelId, startTime, endTime, payMoney, state, paymentVoucher } = getFieldsValue();
    RenewCreatePaymenrecord({
      memberId: defaultData.value.id,
      levelId,
      paymentVoucher,
      startTime,
      endTime,
      payMoney,
      state,
    }).then((res) => {
      callback?.();
      if (state == 1) {
        // 设为已缴费
        _goBack();
      } else {
        sendMsgVisible.value = true;
        sendUserId.value = res.userId; // 发送消息必须取后端返回拼接的ID,否则可能ID不一致
      }
    });
  }
  // 跳转发送消息页面
  const goAddMessage = () => {
    redirectTo({
      name: 'addMessage',
      options: {
        userIds: [unref(sendUserId)],
        typeId: 11, // 写死入会缴费通知类型
      },
    });
  };

  const _goBack = () => {
    navigateBack();
  };

  onLoad<'MemberRenewSet'>((op) => {
    defaultData.value.id = op.id;
    defaultData.value.levelId = op.levelId;
    defaultData.value.levelName = op.levelName;
    defaultData.value.memberName = op.memberName;
    defaultData.value.applyType = op.applyType;
    callback = op.callback;
  });

  const { hasShareImgConfig } = useAppStoreWithOut();

  onShareAppMessage(() => {
    const membershipShare = hasShareImgConfig(ShareTypeEnum.membership);
    return {
      path: setWxSharePath({ name: 'updateMembershipInfo' }),
      imageUrl: membershipShare?.iconUrl,
      title: membershipShare?.desc,
    };
  });
</script>

<style lang="scss" scoped>
  $color-primary: #2878ff;
  .container {
    padding-top: 30rpx;
    // background-color: #fff;
    .report {
      color: $color-primary;
    }

    .top-tips {
      font-size: 28rpx;
      background-color: #fff4e7;
      padding: 20rpx 32rpx;
      color: #ea5e0e;
      margin-bottom: 30rpx;
    }
  }
</style>
